package com.astrob.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;

import com.astrob.activitys.GPSProvider;
import com.astrob.model.LonLat;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.nhc.database.dbmodel.Route;
import com.nhc.database.dbmodel.SystemAllInfo;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.database.manager.MeasureCenter;
import com.nhc.database.manager.QiyaCenter;
import com.nhc.database.manager.SystemCenter;
import com.nhc.model.HCLocationInfo;
import com.nhc.model.NaviTrackSetInfo;
import com.nhc.model.PoiCollectInfo;
import com.nhc.model.SensorSetInfo;
import com.nhc.model.TripDataFileHandle;

import org.greenrobot.greendao.annotation.Transient;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import zuo.biao.library.util.MD5Util;


//保存系统设置 by SharedPreferences
//依设置，输出单位
public class SysUtils {

    Context mContext;

    private static SysUtils instance = new SysUtils();

    public static SysUtils getInstance() {
        return instance;
    }

    public static String[] UNITS_0 = {"公里/小时", "米/秒", "英里/小时", "米/分钟", "英尺/分"};
    public static String[] UNITS_1 = {"公里/米", "英里/英尺", "英里/码", "海里/米", "海里/英尺"};
    public static String[] UNITS_2 = {"平方公里", "公顷", "平方米", "平方英尺", "平方英里", "英亩", "亩"};
    public static String[] UNITS_3 = {"摄氏度", "华氏度"};
    public static String[] UNITS_4 = {"毫巴", "帕", "英寸汞柱", "毫米汞柱"};
    public static String[] UNITS_5 = {"保留小数点后5位", "保留小数点后6位", "保留小数点后7位", "保留小数点后8位"};

    //    public static final String[] COORD_0 = {"WGS84", "BJ54", "XA80", "CGCS2000", "自定义"};
    public static String[] COORD_0 = {"WGS 1984", "北京 1954", "西安 1980", "国家 2000", "自定义"};
    public static String[] COORD_1 = {"d.ddddd°", "d°mm.mmm’", "d°mm’ss.s”", "UTM", "自定义"};
    public static String[] COORD_11 = {"d.ddddd°", "d°mm.mmm’", "d°mm’ss.s”"};


    public void init(Context context) {
        mContext = context;
        UNITS_0 = context.getResources().getStringArray(R.array.units_0);
        UNITS_1 = context.getResources().getStringArray(R.array.units_1);
        UNITS_2 = context.getResources().getStringArray(R.array.units_2);
        UNITS_3 = context.getResources().getStringArray(R.array.units_3);
        UNITS_4 = context.getResources().getStringArray(R.array.units_4);
        UNITS_5 = context.getResources().getStringArray(R.array.units_5);

        COORD_0 = context.getResources().getStringArray(R.array.coord_0);
        COORD_1 = context.getResources().getStringArray(R.array.coord_1);
        loadeUnit();
        loadeCoordSet();
        loadMgrsSet();
        loadeMapSource();
        loadeMeasureParam();
        loadeNaviSet();

    }

    public boolean is240x320 = false;

    //----系统设置----
    private static String SYSINFO = "localinfo";

    private static String PREVIEWLON = "previewLon";
    private static String PREVIEWLAT = "previewLat";
    private static String SHOWTOPINFO = "showtopinfo";
    private static String WAYTRAIL_ID = "waytrail_id";//当前的航迹id，如果有则保存航迹

    //http://qq.ip138.com/converter8.htm  度量衡
    private static String VEL_UNIT = "vel_unit";//0-km/h 1-米／秒 m/s 2-英里／时 mi/h  3-米／分钟 m/min 4-英尺／分 ft/m
    private static String DIS_UNIT = "dis_unit";//0-km/m 1-英里／英尺 mi/ft  2-英里／码 mi/yd 3-海里／米 nmi/m 4-海里／英尺 nmi/ft
    private static String AREA_UNIT = "area_unit";//0-平方公里 km2 1-平方米 m2 2-平方英尺 sq.ft 3-平方英里 sq.mi 4-英亩 acre 5-亩 are
    private static String WENDU_UNIT = "wendu_unit";//0-摄氏 C 1-华氏 F
    private static String QIYA_UNIT = "qiya_unit";//0-毫巴 mba 1-帕 hpa 2-英寸汞柱 in Hg 3-毫米汞柱 Torr = mm Hg
    private static String LL_UNIT = "ll_unit";//0-5位 1-6位 2-7位 3-8位

    //坐标系
    private static String COORD_MODE = "coord_mode";//0-WGS84 1-BJ54 2-XA80 3-CGCS2000 4-自定义
    private static String COORD_FORMAT = "coord_format";//0-d.dd 1-d mm.mm 2-d m ss.ss 3-UTM 4-自定义

    //-------
    //现在地
    public void saveLL(LonLat ll) {
        if (mContext == null || ll == null) {
            return;
        }

        if (Utils.out_of_china(ll.GetLon(), ll.GetLat())) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat(PREVIEWLON,
                (float) ll.GetLon());
        editor.putFloat(PREVIEWLAT,
                (float) ll.GetLat());
        editor.commit();
    }

    public LonLat getLL() {
        if (mContext == null) {
            return new LonLat();
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        double lon = sp.getFloat(PREVIEWLON, 0);
        double lat = sp.getFloat(PREVIEWLAT, 0);

        LonLat ll = new LonLat(lon, lat);
        if (Utils.out_of_china(ll.GetLon(), ll.GetLat())) {
            return new LonLat(116.32722222, 39.98638889);//无效则设置一个默认点
        }
        return ll;
    }

    //地图topinfo
    public boolean getIsShowtopinfo() {
        if (mContext == null) {
            return true;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        boolean showtopinfo = sp.getBoolean(SHOWTOPINFO, true);
        return showtopinfo;
    }

    public void setIsShowtopinfo(boolean showtopinfo) {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(SHOWTOPINFO, showtopinfo);
        editor.commit();
    }

    //当前航迹id
    public void saveWaytrailID(long id) {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(WAYTRAIL_ID, id);
        editor.commit();
    }

    public long getWaytrailID() {
        if (mContext == null) {
            return 0L;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        long id = sp.getLong(WAYTRAIL_ID, 0L);
        return id;
    }

    public int coord_mode = 0;
    public int coord_format = 2;

    public String getCoordModeStr() {
        if (coord_mode < 0 || coord_mode >= COORD_0.length) {
            coord_mode = 0;
        }
        return COORD_0[coord_mode];
    }

    public String getCoordFormatStr() {
        if (coord_format < 0 || coord_format >= COORD_1.length) {
            coord_format = 0;
        }
        return COORD_1[coord_format];
    }

    public void resetCoordSet() {
        coord_format = 2;
        coord_mode = 0;

        saveCoordSet();
    }

    //坐标系
    public void saveCoordSet() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(COORD_MODE, coord_mode);
        editor.putInt(COORD_FORMAT, coord_format);
        editor.commit();
    }

    public void loadeCoordSet() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        coord_mode = sp.getInt(COORD_MODE, coord_mode);
        coord_format = sp.getInt(COORD_FORMAT, coord_format);
    }

    //mgrsparamset
    public int mgrsaccuracy = 1;//1,10,100,1000,10000
    public int mgrsgridtype = 1;//1,2,3

    public String getMgrsaccuracyStr() {
        return mgrsaccuracy + "";
    }

    public String getMgrsgridtypeStr() {
        return "MGRS-" + mgrsgridtype;
    }

    public void resetMgrsSet() {
        mgrsaccuracy = 1;
        mgrsgridtype = 1;

        saveMgrsSet();
    }

    //坐标系
    private static String MGRSSET_ACC = "mgrsaccuracy";
    private static String MGRSSET_GRID = "mgrsgridtype";

    public void saveMgrsSet() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(MGRSSET_ACC, mgrsaccuracy);
        editor.putInt(MGRSSET_GRID, mgrsgridtype);
        editor.commit();
    }

    public void loadMgrsSet() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        mgrsaccuracy = sp.getInt(MGRSSET_ACC, mgrsaccuracy);
        mgrsgridtype = sp.getInt(MGRSSET_GRID, mgrsgridtype);
    }

    //单位
    public int vel_mode = 0;
    public int dis_mode = 0;
    public int area_mode = 2;
    public int wendu_mode = 0;
    public int qiya_mode = 3;
    public int ll_mode = 0;

    public String getVelUnitStr() {
        if (vel_mode < 0 || vel_mode >= UNITS_0.length) {
            vel_mode = 0;
        }
        return UNITS_0[vel_mode];
    }

    public String getDisUnitStr() {
        if (dis_mode < 0 || dis_mode >= UNITS_1.length) {
            dis_mode = 0;
        }
        return UNITS_1[dis_mode];
    }

    public String getAreaUnitStr() {
        if (area_mode < 0 || area_mode >= UNITS_2.length) {
            area_mode = 0;
        }
        return UNITS_2[area_mode];
    }

    public String getWenduUnitStr() {
        if (wendu_mode < 0 || wendu_mode >= UNITS_3.length) {
            wendu_mode = 0;
        }
        return UNITS_3[wendu_mode];
    }

    public String getQiyaUnitStr() {
        if (qiya_mode < 0 || qiya_mode >= UNITS_4.length) {
            qiya_mode = 0;
        }
        return UNITS_4[qiya_mode];
    }

    public String getLLUnitStr() {
        if (ll_mode < 0 || ll_mode >= UNITS_5.length) {
            ll_mode = 0;
        }
        return UNITS_5[ll_mode];
    }

    public void resetUnit() {
        vel_mode = 0;
        dis_mode = 0;
        area_mode = 2;
        wendu_mode = 0;
        qiya_mode = 0;
        ll_mode = 0;

        saveUnit();
    }

    public void saveUnit() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(VEL_UNIT, vel_mode);
        editor.putInt(DIS_UNIT, dis_mode);
        editor.putInt(AREA_UNIT, area_mode);
        editor.putInt(WENDU_UNIT, wendu_mode);
        editor.putInt(QIYA_UNIT, qiya_mode);
        editor.putInt(LL_UNIT, ll_mode);
        editor.commit();
    }

    public void loadeUnit() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        vel_mode = sp.getInt(VEL_UNIT, vel_mode);
        dis_mode = sp.getInt(DIS_UNIT, dis_mode);
        area_mode = sp.getInt(AREA_UNIT, area_mode);
        wendu_mode = sp.getInt(WENDU_UNIT, wendu_mode);
        qiya_mode = sp.getInt(QIYA_UNIT, qiya_mode);
        ll_mode = sp.getInt(LL_UNIT, ll_mode);
    }

    //设置航线导航index
    public void startRouteNavi() {
        Route routeNavi = DBDataCenter.getInstance().routeNavi;
        if (routeNavi == null || navi_mode0 == 0 || routeNavi.waypointList == null) {
            return;
        }

        //就近导航
        LonLat llCar = getLL();
        int size = routeNavi.waypointList.size();
        DBDataCenter.getInstance().routeNaviIndex = 0;
        double dis = 99999999;
        for (int i = 0; i < size; i++) {
            double disT = Start.getInstance().MapKit().getDistance(llCar, routeNavi.waypointList.get(i).getLL());
            if (disT < dis) {
                dis = disT;
                DBDataCenter.getInstance().routeNaviIndex = i;
            }
        }
    }

    //导航设置
    public int navi_mode0 = 0;//0-逐点导航 1-就近点导航
    public int navi_mode1 = 1;//0-直接导航 1-道路导航
    public int navi_mode2 = 0;//0-驾车 1-步行

    public void saveNaviSet() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("navi_mode0", navi_mode0);
        editor.putInt("navi_mode1", navi_mode1);
        editor.putInt("navi_mode2", navi_mode2);
        editor.commit();
    }

    public void loadeNaviSet() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        navi_mode0 = sp.getInt("navi_mode0", navi_mode0);
        navi_mode1 = sp.getInt("navi_mode1", navi_mode1);
        navi_mode2 = sp.getInt("navi_mode2", navi_mode2);
    }

    public void resetNaviSet() {
        navi_mode0 = 0;
        navi_mode1 = 0;
        saveNaviSet();
    }

    //栅格图下载设置，是否要保存？
    public int pZoomMin = 3;
    public int pZoomMax = 16;
    public String downloadmapdbname = "";//下载后sqlite的copy文件重命名；如果是没有名称说明当前无下载任务


    //地图源
    private static String MAPSOURCE = "mapsource";
    private static String MAPFILEPATH1 = "mapfilepath1";
    private static String MAPFILEPATH2 = "mapfilepath2";
    private static String MAPFILEPATH3 = "mapfilepath3";
    private static String MAPFILEPATH4 = "mapfilepath4";
    //1000-smf 1001-mapsforge 渲染的地形图 1002-gemf （or 所有离线格式） 1003-mbtiles 1004-zip
    //在线图 array-"maps_online"
    public int mapsource = 1000;
    public String mapfilepath1 = "";//对应mapsforgeFile
    public String mapfilepath2 = "";//离线栅格图
    public String mapfilepath3 = "";
    public String mapfilepath4 = "";
    public File mapsforgeFile = new File(Environment.getExternalStorageDirectory() + "/BHCMapper/mapsforge", "china.map");

    public void resetMapSource() {
        mapsource = 1000;
        saveMapSource();
    }

    public void saveMapSource() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(MAPSOURCE, mapsource);
        editor.putString(MAPFILEPATH1, mapfilepath1);
        editor.putString(MAPFILEPATH2, mapfilepath2);
        editor.putString(MAPFILEPATH3, mapfilepath3);
        editor.putString(MAPFILEPATH4, mapfilepath4);
        editor.commit();
    }

    public void loadeMapSource() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        mapsource = sp.getInt(MAPSOURCE, mapsource);
        mapfilepath1 = sp.getString(MAPFILEPATH1, mapfilepath1);
        mapfilepath2 = sp.getString(MAPFILEPATH2, mapfilepath2);
        mapfilepath3 = sp.getString(MAPFILEPATH3, mapfilepath3);
        mapfilepath4 = sp.getString(MAPFILEPATH3, mapfilepath4);

        if (mapfilepath1.length() > 1) {
            mapsforgeFile = new File(mapfilepath1);
            if (!mapsforgeFile.exists()) {
                mapfilepath1 = "";
            }
        }
            
        if (mapfilepath1.length() < 1) {
            mapfilepath1 = Start.RUNDIR + "mapsforge/china.map";
            mapsforgeFile = new File(mapfilepath1);
            if (!mapsforgeFile.exists()) {
                mapfilepath1 = "/mnt/sdcard2/BHCMapper/mapsforge/china.map";
                mapsforgeFile = new File(mapfilepath1);
            }
            saveMapSource();
        }
    }

    //等宽测量和坡面测量
    public double measure_width = 0; //->等宽面积的宽度
    public double measure_slopeangle = 0;//斜坡角度

    public void saveMeasureParam() {
        if (mContext == null) {
            return;
        }

        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("measure_width", measure_width + "");
        editor.putString("measure_slopeangle", measure_slopeangle + "");
        editor.commit();
    }

    public void loadeMeasureParam() {
        if (mContext == null) {
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(
                SYSINFO, Context.MODE_PRIVATE);
        measure_width = Double.valueOf(sp.getString("measure_width", measure_width + ""));
        measure_slopeangle = Double.valueOf(sp.getString("measure_slopeangle", measure_slopeangle + ""));
    }

    //--------------------其它函数
    //0-平方公里 km2 1-平方米 m2 2-平方英尺 sq.ft 3-平方英里 sq.mi 4-英亩 acre 5-亩 are
    // area -- 平方米
    public String[] getAreaStr(double area) {
        String strArea = "";
        String strUnit = "";
        switch (area_mode) {
            default:
            case 0:
                strArea = new DecimalFormat("0.0").format(area / 1000000);
                strUnit = " k㎡";
                break;
            case 1:
                strArea = new DecimalFormat("0.0").format(area / 10000);
                strUnit = " hm²";
                break;
            case 2:
                strArea = new DecimalFormat("0.0").format(area);
                if (area > 1000) {
                    strArea = new DecimalFormat("0").format(area);
                }
                strUnit = " ㎡";
                break;
            case 3:
                strArea = new DecimalFormat("0.0").format(area / 0.0929030);
                strUnit = " sq.ft";
                break;
            case 4:
                strArea = new DecimalFormat("0.0").format(area / 2589988.110336);
                strUnit = " sq.mi";
                break;
            case 5:
                strArea = new DecimalFormat("0.0").format(area / 4046.8564224);
                strUnit = " acre";
                break;
            case 6:
                strArea = new DecimalFormat("0.0").format(area / 666.6666667);
                strUnit = mContext.getString(R.string.nullmu);
                break;
        }

        String[] SS = {strArea, strUnit};
        return SS;
    }

    ////0-毫巴 mba／hpa 1-帕 pa 2-英寸汞柱 in Hg 3-毫米汞柱 Torr = mm Hg
    //qiya -- pa
    public String[] getQiyaStr(double qiya) {
        String strQiya = "";
        String strUnit = "";
        switch (qiya_mode) {
            default:
            case 0:
                strQiya = new DecimalFormat("0.0").format(qiya / 100);
                strUnit = " mba";
                break;
            case 1:
                strQiya = new DecimalFormat("0.0").format(qiya);
                strUnit = " pa";
                break;
            case 2:
                strQiya = new DecimalFormat("0.0").format(qiya / 3386.3882);
                strUnit = " in Hg";
                break;
            case 3:
                strQiya = new DecimalFormat("0.0").format(qiya / 133.32237);
                strUnit = " mm Hg";
                break;
        }

        String[] SS = {strQiya, strUnit};
        return SS;
    }

    //0-摄氏 C 1-华氏 F
    //wendu -- 摄氏度
    public String[] getWenduStr(double wendu) {
        String strWendu = "";
        String strUnit = "";
        switch (wendu_mode) {
            default:
            case 0:
                strWendu = new DecimalFormat("0.0").format(wendu);
                strUnit = " °C";
                break;
            case 1:
                strWendu = new DecimalFormat("0.0").format(wendu * 1.8 + 32);
                strUnit = " °F";
                break;
        }

        String[] SS = {strWendu, strUnit};
        return SS;
    }

    ////0-km/m 1-英里／英尺 mi/ft  2-英里／码 mi/yd 3-海里／米 nmi/m 4-海里／英尺 nmi/ft
    //distance --- 米
    public String[] getDistanceStr(int distance) {
        String strDistance = "";
        String strUnit = "";

        switch (dis_mode) {
            default:
            case 0:
                if (distance >= 1000000) {
                    strDistance = new DecimalFormat("0").format(distance / 1000);
                    strUnit = " km";
                } else if (distance >= 1000) {
                    strDistance = new DecimalFormat("0.00").format(distance / 1000.0);
                    strUnit = " km";
                } else {
                    strDistance = new DecimalFormat("0").format(distance);
                    strUnit = " m";
                }
                break;
            case 1: {
                double distanceA = distance * 3.2808399;
                if (distanceA >= 5280000) {
                    strDistance = new DecimalFormat("0").format(distanceA / 52800);
                    strUnit = " mi";
                } else if (distance >= 5280) {
                    strDistance = new DecimalFormat("0.00").format(distanceA / 52800.0);
                    strUnit = " mi";
                } else {
                    strDistance = new DecimalFormat("0").format(distanceA);
                    strUnit = " ft";
                }
            }
            break;
            case 2: {
                double distanceA = distance * 1.0936133;
                if (distanceA >= 1760000) {
                    strDistance = new DecimalFormat("0").format(distanceA / 1760);
                    strUnit = " mi";
                } else if (distance >= 1760) {
                    strDistance = new DecimalFormat("0.00").format(distanceA / 1760.0);
                    strUnit = " mi";
                } else {
                    strDistance = new DecimalFormat("0").format(distanceA);
                    strUnit = " yd";
                }
            }
            break;
            case 3:
                if (distance >= 1852000) {
                    strDistance = new DecimalFormat("0").format(distance / 1852);
                    strUnit = " nmi";
                } else if (distance >= 1852) {
                    strDistance = new DecimalFormat("0.00").format(distance / 1852.0);
                    strUnit = " nmi";
                } else {
                    strDistance = new DecimalFormat("0").format(distance);
                    strUnit = " m";
                }
                break;
            case 4: {
                double distanceA = distance * 3.2808399;
                if (distanceA >= 6076200) {
                    strDistance = new DecimalFormat("0").format(distanceA / 6076.1154856);
                    strUnit = " mi";
                } else if (distance >= 6077) {
                    strDistance = new DecimalFormat("0.00").format(distanceA / 6076.1154856);
                    strUnit = " mi";
                } else {
                    strDistance = new DecimalFormat("0").format(distanceA);
                    strUnit = " ft";
                }
            }
            break;
        }

        String[] SS = {strDistance, strUnit};
        return SS;
    }

    //获取高度，精确到小数点后两位
    public String[] getAltitudeStr(double altitude) {
        String strAlt = "";
        String strUnit = "";

        switch (dis_mode) {
            default:
            case 3:
            case 0:
                strAlt = new DecimalFormat("0.00").format(altitude);
                strUnit = " m";
                break;
            case 4:
            case 1: {
                altitude = altitude * 3.2808399;
                strAlt = new DecimalFormat("0.00").format(altitude);
                strUnit = " ft";
            }
            break;
            case 2: {
                altitude = altitude * 1.0936133;
                strAlt = new DecimalFormat("0").format(altitude);
                strUnit = " yd";
            }
            break;
        }

        String[] SS = {strAlt, strUnit};
        return SS;
    }

    //vel -- 米／秒
    //0-km/h 1-米／秒 m/s 2-英里／时 mi/h  3-米／分钟 m/min 4-英尺／分 ft/min
    public String[] getVelStr(double vel) {

        String strVel = "";
        String strUnit = "";

        switch (vel_mode) {
            default:
            case 0:
                strVel = new DecimalFormat("0.0").format((int) (vel * 3.6));
                strUnit = " km/h";
                break;
            case 1:
                strVel = new DecimalFormat("0.0").format(vel);
                strUnit = " m/s";
                break;
            case 2:
                strVel = new DecimalFormat("0.0").format((int) (vel * 3.6 / 1.609344));
                strUnit = " mi/h";
                break;
            case 3:
                strVel = new DecimalFormat("0.0").format(vel*60);
                strUnit = " m/min";
                break;
            case 4:
                strVel = new DecimalFormat("0.0").format(vel * 60 * 3.2808399);
                strUnit = " ft/min";
                break;
        }

        String[] SS = {strVel, strUnit};
        return SS;
    }

    public String getLLStr(LonLat ll) {
        if (ll == null) {
            return "";
        }

        int format = coord_format;

        LonLat llA = new LonLat(ll.GetLon(), ll.GetLat());

//        if (coord_format > 2 && (coord_mode == 0 || coord_mode == 3)) {
//            format = 2;//WGS84和国家2000没有大地坐标格式
//        }

        if (coord_format <= 2 && coord_mode != 0 && coord_mode != 3) {
            //大地坐标参考椭球，坐标投影格式需>=3
//            format = 3;
        }

//        {"d.ddddd°", "d°mm.mmm’", "d°mm’ss.s”", "UTM", "自定义"}
        String weisu = "0.00000";
        switch (ll_mode) {
            default:
            case 0:
                break;
            case 1:
                weisu = "0.000000";
                break;
            case 2:
                weisu = "0.0000000";
                break;
            case 3:
                weisu = "0.00000000";
                break;
        }

        HCLocationInfo ci = CoordChange.getInstance().getHCL(coord_mode, llA, format);
        llA = ci.getLL();

        String strLL = "";
        if (format == 0) {
            double lon = llA.GetLon();
            double lat = llA.GetLat();
            String strLon = new DecimalFormat(weisu).format(Math.abs(lon)) + "°" + (lon > 0 ? " E" : " W");
            String strLat = new DecimalFormat(weisu).format(Math.abs(lat)) + "°" + (lat > 0 ? " N" : " S");
            strLL = strLat + "\n" + strLon;
        } else if (format == 1) {
            int latD = (int) llA.GetLat();
            int lonD = (int) llA.GetLon();
            float latF = (float) (llA.GetLat() - latD) * 60;
            float lonF = (float) (llA.GetLon() - lonD) * 60;
            strLL = Math.abs(latD) + "°" + new DecimalFormat(weisu).format(latF) + "’ " + (latD > 0 ? " N " : " S ")
                    + "\n" + Math.abs(lonD) + "°" + new DecimalFormat(weisu).format(lonF) + "’ " + (lonD > 0 ? " E" : " W");
        } else if (format == 2) {
            Map<String, String> DMS = getLLDMS(llA);
            if (DMS != null) {
                strLL = DMS.get("lat") + "\n" + DMS.get("lon");
            }
        } else if (format >= 3) {
            Map<String, String> DMS = ci.getLLStr();
            if (DMS != null) {
                strLL = DMS.get("lat") + "\n" + DMS.get("lon");
            }
        }

        return strLL;
    }

    public Map<String, String> getLLDMS(LonLat ll) {
        return Utils.LL2DMS(ll);
    }

    public String getTimeStr(long datetime) {
        if (datetime == 0) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-M-dd HH:mm:ss");
        Date curDate = new Date(datetime);
        String res = formatter.format(curDate);
        return res;
    }

    public String getDateStr(long datetime) {
        if (datetime == 0) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-M-dd");
        Date curDate = new Date(datetime);
        String res = formatter.format(curDate);
        return res;
    }


    ///--------------

    ////-------------
    int _hXqiyaHNum = 0;//气压高度和GPS高度偏差超过10米的次数；10次自动校准

    //保存航迹
    public boolean saveTrackPoint(TrackPoint trackPoint) {
        //trackPoint--有效的已经定位的GPS点，时间正确的
        if (trackPoint == null) {
            return false;
        }

        //低速则不记录，不需要每秒记录--精度低的也可以过滤，
        if (trackPoint.getSpeed() * 3.6 < 2 || trackPoint.getAccuracy() > 40) {
            return false;
        }

        //高度使用气压高度
        if (NaviTrackSetInfo.getInstance().isUseqiyagd() && QiyaCenter.getInstance()._thisQiyaInfo != null) {
            double H = trackPoint.getAltitude();//GPS高度
            double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
            double sPV = QiyaCenter.getInstance()._thisQiyaInfo.getSPV();
            int X = Math.abs((int) (qiyaH - H));
            if (X < 100 || H == 0) {
                //气压高度误差太大；可能气压高度是不准确的则不用
                trackPoint.setAltitude(qiyaH);
            }

            if (X > 10 && trackPoint.getAccuracy() < 10 && H != 0) {
                _hXqiyaHNum++;
                if (_hXqiyaHNum > 10) {
                    _hXqiyaHNum = 0;
                    SensorSetInfo.getInstance().useHeightCalibration(H, sPV);
                }
            } else {
                _hXqiyaHNum = 0;
            }

        }

        //自动采集航点
        saveWayPoint(trackPoint.getLL());

        //实时测量面积
        saveMeasureRT(trackPoint);//

        TripDataFileHandle.getInstance().mTripDatainfo.setCurrentTp(trackPoint);

        //每30秒保存一次
        long second = (trackPoint.getDatetime() - TripDataFileHandle.getInstance().mTripDatainfo.getStarttime()) / 1000;
        if (second > 30 && second < 10000) {
            TripDataFileHandle.getInstance().save();
        }

        if (DBDataCenter.getInstance().wayTrailThis == null
                || DBDataCenter.getInstance().wayTrailThis.getIsPause()) {
            return DBDataCenter.getInstance().saveTrackPoint(trackPoint);//记录行程点 waytrail_id==0
        }

        //--需记录航迹--
        Long waytrail_id = DBDataCenter.getInstance().getThisWayTrailID();//满足航迹记录条件则使用
        //保存条件， 按距离，还是按时间
        int mode = NaviTrackSetInfo.getInstance().getSavemode();
        TrackPoint lastTrackPoint = DBDataCenter.getInstance().lastTrackPoint;
        int interval = 1;
        double distance = 0;
        double speed = trackPoint.getSpeed() * 3.6;
        boolean isAdd = false;
        long lasttime = 0;
        if (lastTrackPoint != null) {
            lasttime = lastTrackPoint.getDatetime();
            interval = (int) (trackPoint.getDatetime() - lastTrackPoint.getDatetime()) / 1000;
            distance = Start.getInstance().MapKit().getDistance(trackPoint.getLL(), lastTrackPoint.getLL());
            //自动：时速小于10km时，按5s间隔，时速10KM-30KM时，按3s间隔，时速大于30KM时，按1s间隔
            switch (mode) {
                default:
                case 0://时间
                    if (interval >= NaviTrackSetInfo.getInstance().getInterval_T()) {
                        trackPoint.setWaytrail_id(waytrail_id);
                        isAdd = true;
                    }
                    break;
                case 1://"距离"
                    if (distance >= NaviTrackSetInfo.getInstance().getInterval_D()) {
                        trackPoint.setWaytrail_id(waytrail_id);
                        isAdd = true;
                    }
                    break;
                case 2:
                    if (speed <= 10) {
                        if (interval >= 5) {
                            trackPoint.setWaytrail_id(waytrail_id);
                            isAdd = true;
                        }
                    } else if (speed <= 30) {
                        if (interval >= 3) {
                            trackPoint.setWaytrail_id(waytrail_id);
                            isAdd = true;
                        }
                    } else {
                        trackPoint.setWaytrail_id(waytrail_id);
                        isAdd = true;
                    }
                    break;
            }
        } else {
            trackPoint.setWaytrail_id(waytrail_id);
            isAdd = true;
        }

        if (isAdd) {
            DBDataCenter.getInstance().lastTrackPoint = trackPoint;
        }

        if (DBDataCenter.getInstance().wayTrailThis.trackPointList == null) {
            DBDataCenter.getInstance().wayTrailThis.trackPointList = new ArrayList<TrackPoint>();
        } else {
            DBDataCenter.getInstance().wayTrailThis.trackPointList.add(trackPoint);
        }

        int automode = NaviTrackSetInfo.getInstance().getAutomode();
        boolean needsave = false;

        long starttime = DBDataCenter.getInstance().wayTrailThis.getStarttime();
        long thistime = trackPoint.getDatetime();
        long xtime = (thistime - starttime) / (1000 * 3600 * 24);//x天
        //1-每天  2-每周
//        if (automode == 1 && xtime >= 1) {
        if (automode == 1 && lasttime > 0) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date0 = new Date(lasttime);
            Date date1 = new Date(thistime);
            String strDate0 = formatter.format(date0);
            String strDate1 = formatter.format(date1);
            if (strDate0.compareTo(strDate1) != 0) {
                needsave = true;
                String name = SysUtils.getInstance().getTimeStr(lasttime);
                DBDataCenter.getInstance().wayTrailThis.setName(name);
                DBDataCenter.getInstance().wayTrailThis.setEndtime(lasttime);
            }
        } else if (automode == 2 && xtime >= 30) {
            needsave = true;
        }

        if (needsave) {
            DBDataCenter.getInstance().closeThisWayTrail();
            DBDataCenter.getInstance().startThisWayTrail();
        }

        return DBDataCenter.getInstance().saveTrackPoint(trackPoint);
    }

    private WayPoint lastWp;

    private void saveWayPoint(LonLat ll) {
        if (ll == null) {
            return;
        }

        int autocollect = PoiCollectInfo.getInstance().getAutocollect();
        if (autocollect == 0) {
            return;
        }

        WayPoint wp = new WayPoint("auto-" + SysUtils.getInstance().getTimeStr(System.currentTimeMillis()), ll);
        wp.setAltitude(GPSProvider.getInstance().getAltitude());
        if (QiyaCenter.getInstance()._thisQiyaInfo != null) {
            double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
            if (Math.abs((int) (qiyaH - wp.getAltitude())) < 100) {
                //气压高度误差太大；可能气压高度是不准确的则不用
                wp.setAltitude(qiyaH);
            }
        }

        if (lastWp != null) {
            int interval = (int) (wp.getDatetime() - lastWp.getDatetime()) / 1000;
            double distance = Start.getInstance().MapKit().getDistance(wp.getLL(), lastWp.getLL());
            switch (autocollect) {
                default:
                    break;
                case 1://时间
                    if (interval >= PoiCollectInfo.getInstance().getIntervalmode_t()) {
                        DBDataCenter.getInstance().saveWayPoint(wp);
                        lastWp = wp;
                    }
                    break;
                case 2://"距离"
                    if (distance >= PoiCollectInfo.getInstance().getIntervalmode_d()) {
                        DBDataCenter.getInstance().saveWayPoint(wp);
                        lastWp = wp;
                    }
                    break;
            }
        } else {
            DBDataCenter.getInstance().saveWayPoint(wp);
            lastWp = wp;
        }
    }

    public int _realtimeArea = -1;// 实时测量 0-暂停 1-开始

    private void saveMeasureRT(TrackPoint trackPoint) {
        if (_realtimeArea == 0 || trackPoint == null || MeasureCenter.getInstance().measureRT == null
                || MeasureCenter.getInstance().measureRT.measurePtList == null) {
            return;
        }

        if (trackPoint.getAccuracy() < 13 || MeasureCenter.getInstance().measureRT.measurePtList.size() == 0) {
            MeasureCenter.getInstance().measureRT.add(trackPoint.getLL(), trackPoint.getAltitude());
        }
    }

}
